// 在 D 天内送达包裹的能力

import Foundation

func shipWithinDays(_ weights: [Int], _ days: Int) -> Int {
//  weights的总和
    var right = weights.reduce(0, +)
//  weights的最大值
    var left = weights.max()!
    
    while left < right {
        let mid = left + (right - left)/2
        if needDay(weights, mid) > days {
            left = mid + 1
        }
        else {
            right = mid
        }
    }
    return left
}

func needDay(_ weights: [Int], _ num: Int) -> Int {
    print("num",num)
    var day = 1
    var totals = 0
    for i in 0..<weights.count {
        if totals + weights[i] > num {
            // 超出载重就重新记零，并且day+1
            totals = 0
            day += 1
        }
        totals += weights[i]
    }
    print("days",day)
    return day
}
